﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace DNEL.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class ControlExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="action"></param>
        public static void RunInUIThread(this Control ctl, Action action)
        {
            if (ctl.InvokeRequired)
            {
                ctl.Invoke(action);
            }
            else
            {
                action();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="Msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ctl"></param>
        /// <example>
        /// Call in the control's DragOver event.
        /// </example>
        public static void Scroll(this Control ctl)
        {
            var pt = ctl.PointToClient(Cursor.Position);

            if ((pt.Y + DNELSettings.ScrollHeight) > ctl.Height)
            {
                // scroll down
                SendMessage(ctl.Handle, 277, (IntPtr)1, (IntPtr)0);
            }
            else if (pt.Y < DNELSettings.ScrollHeight)
            {
                // scroll up
                SendMessage(ctl.Handle, 277, (IntPtr)0, (IntPtr)0);
            }
        }
    }
}
